/**
 * 
 */
package io.dora.lb;

import java.util.Random;

import org.apache.commons.lang.StringUtils;

/**
 * 负载均衡随机实现
 * 
 * @author zhaohongbo
 *
 */
public class RandomInvokeLoadBalance implements InvokeLoadBalance {

	/** 服务主机 */
	private String serviceHosts;

	/** 随机数生成 */
	private Random rand;
	
	/** 服务主机列表 */
	private String[] hostsArrays;
	
	public RandomInvokeLoadBalance(String serviceHosts) {
		this.serviceHosts = serviceHosts;
		this.init();
	}

	@Override
	public String select() {
		return doSelect();
	}
	
	private void init() {
		hostsArrays = StringUtils.split(serviceHosts, ",");
		rand = new Random();
	}
	
	private String doSelect() {
		String selected = hostsArrays[rand.nextInt(hostsArrays.length)];
		return selected;
	}

	@Override
	public String[] getProviderHosts() {
		return hostsArrays;
	}
}
